import { defineStore } from 'pinia';
import { pathJoin } from 'src/api/SysApi';
import { getFile, saveFile } from 'src/api/FileApi';
import { useConfigStore }    from 'stores/configStore';

export const useFileStore = defineStore('file', () => {
  const getFileContentByPath = (path: string) => {
    return new Promise((resolve) => {
      getFile(path, false).then((r: string) => {
        resolve(r);
      });
    });
  };
  const getFileContentByName = (name: string) => {
    return new Promise(async (resolve) => {
      getFile(
        pathJoin(
          <string>(await useConfigStore().getConfig())?.templateFilePath,
          name
        ),
        false
      ).then((r: string) => {
        resolve(r);
      });
    });
  };
  const saveFileContentByPath = (path: string, data: string) => {
    return new Promise((resolve) => {
      saveFile(path, data).then((r: string) => {
        resolve(r);
      });
    });
  };
  const saveFileContentByName = (name: string, data: string) => {
    return new Promise(async (resolve) => {
      saveFile(
        pathJoin(
          <string>(await useConfigStore().getConfig())?.templateFilePath,
          'file',
          name
        ),
        data
      ).then((r: string) => {
        resolve(r);
      });
    });
  };
  return {
    getFileContentByPath,
    getFileContentByName,
    saveFileContentByPath,
    saveFileContentByName,
  };
});
